package com.egg.mall.controller.web;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.egg.auth.feign.AuthUserFeignClient;
import com.egg.auth.model.request.web.UserPagePostFeign;
import com.egg.auth.model.response.web.UserPage;
import com.egg.common.core.model.controller.WebController;
import com.egg.common.core.model.request.StateRequest;
import com.egg.common.core.model.response.PageData;
import com.egg.common.core.model.response.ResponseData;
import com.egg.common.util.JsonUtil;
import com.egg.mall.entity.sku.orders.SkuOrders;
import com.egg.mall.enums.OrderStateEnum;
import com.egg.mall.model.request.OrderPostOrPut;
import com.egg.mall.model.response.web.OrderPage;
import com.egg.mall.service.sku.order.ISkuOrdersService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author east
 * @since 2022-08-27
 */
@Slf4j
@Api(tags = WebController.API_PREFIX + "订单")
@RestController
@RequestMapping("/sku/orders")
public class WebSkuOrdersController extends WebController {


    @Autowired
    private ISkuOrdersService skuOrdersService;
    @Autowired(required = false)
    private AuthUserFeignClient authUserFeignClient;


    @ApiOperation(value = "订单新增并拉起支付")
    @PostMapping
    public ResponseData<String> skuOrdersAddAndPayPost(@RequestBody OrderPostOrPut param) {
        String pay = skuOrdersService.addAndPay(param);
        return ResponseData.success(pay);
    }

    @ApiOperation(value = "订单拉起支付")
    @GetMapping("/{id}/pay")
    public ResponseData<String> skuOrdersPayGet(
            @ApiParam(value = "订单ID", required = true) @PathVariable String id
            , @ApiParam(value = "支付类型", required = true) @RequestParam(value = "payType") String payType
            , @ApiParam(value = "客户端类型", required = true) @RequestParam(value = "clientType") String clientType
    ) {
        String pay = skuOrdersService.pay(id, payType, clientType);
        return ResponseData.success(pay);
    }

    @ApiOperation(value = "订单分页")
    @GetMapping("/page")
    public ResponseData<PageData<OrderPage>> skuOrdersPageGet(
            @ApiParam(value = "页数", required = true) @RequestParam(value = "current", defaultValue = "1") Integer current
            , @ApiParam(value = "页长", required = true) @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize
    ) {
        LambdaQueryWrapper<SkuOrders> qw = skuOrdersService.buildLambdaSortQw();
        Page<SkuOrders> dbPage = skuOrdersService.page(new Page<>(current, pageSize), qw);
        if (ObjectUtil.isEmpty(dbPage.getRecords())) {
            return ResponseData.success(new PageData<>(dbPage));
        }
        Map<Long, String> userMap = new HashMap<>();
        UserPagePostFeign userPagePostFeign = new UserPagePostFeign();
        userPagePostFeign.setIds(dbPage.getRecords().stream().map(o -> o.getUserId()).distinct().collect(Collectors.toList()));
        ResponseData<PageData<UserPage>> userRd = authUserFeignClient.userPagePost(userPagePostFeign);
        if (userRd.isSuccess()) {
            userMap = userRd.getData().getList().stream().collect(Collectors.toMap(o -> o.getId(), o -> o.getNickname()));
        }
        List<OrderPage> list = new ArrayList<>();
        for (SkuOrders skuOrders : dbPage.getRecords()) {
            OrderPage temp = JsonUtil.objToObj(skuOrders, OrderPage.class);
            temp.setUserNickname(userMap.getOrDefault(skuOrders.getUserId(), ""));
            list.add(temp);
        }
        return ResponseData.success(new PageData<>(dbPage, list));
    }

    @ApiOperation(value = "订单详情")
    @GetMapping("/{id}/info")
    public ResponseData<Object> skuOrdersInfoGet(
            @ApiParam(value = "订单主键ID", required = true) @PathVariable String id
    ) {
        SkuOrders dbInfo = skuOrdersService.baseGetById(id);
        // TODO: 转换响应类逻辑 dbInfo To Object
        Object objInfo = new Object();
        return ResponseData.success(objInfo);
    }

    @ApiOperation(value = "订单编辑")
    @PutMapping("/{id}")
    public ResponseData<String> skuOrdersPut(
            @ApiParam(value = "订单主键ID", required = true) @PathVariable String id
            , @RequestBody Object edit
    ) {
        SkuOrders exist = skuOrdersService.baseGetById(id);
        // TODO: 转换请求类逻辑  edit To Info
        SkuOrders info = new SkuOrders();
        info.setId(exist.getId());
        skuOrdersService.baseEdit(info);
        return ResponseData.success(exist.getId().toString());
    }

    @ApiOperation(value = "订单删除")
    @DeleteMapping
    public ResponseData<String> skuOrdersDel(
            @ApiParam(value = "ID集合", required = true) @RequestParam(value = "ids") Collection<String> ids
    ) {
        skuOrdersService.baseDel(
                ids.stream().filter(o -> ObjectUtil.isNotEmpty(o)).collect(Collectors.toSet())
        );
        return ResponseData.success();
    }

    @ApiOperation(value = "订单编辑状态")
    @PatchMapping("/{id}/state")
    public ResponseData<String> skuOrdersStatePut(
            @ApiParam(value = "订单主键ID", required = true) @PathVariable String id
            , @RequestBody StateRequest param
    ) {
        OrderStateEnum nextState = OrderStateEnum.getByCode(param.getState());
        skuOrdersService.editState(id, nextState);
        return ResponseData.success();
    }
}

